IF OBJECT_ID(N'ssf.cmd_dir_basename') IS NOT NULL
	DROP FUNCTION ssf.cmd_dir_basename
GO

CREATE FUNCTION ssf.cmd_dir_basename (
	@path NVARCHAR(2048)
	, @suffix NVARCHAR(128)
)
RETURNS NVARCHAR(2048)
AS
/*
<object_header>

<object_summary>
	<purpose><![CDATA[
Return @path with any leading directory components removed.
If specified, also remove trailing @suffix.
	]]></purpose>
</object_summary>

</object_header>
*/
BEGIN
	IF NULLIF(@path, N'') IS NULL
		RETURN NULL
	IF CHARINDEX(N'\', @path) = 0
		RETURN @path
	
	DECLARE @htap NVARCHAR(2048) = REVERSE(@path)
	DECLARE @i SMALLINT = CHARINDEX(N'\', @htap)
	DECLARE @name NVARCHAR(2048)
	
	IF @i = 1
		RETURN N'\'
	
	IF SUBSTRING(@htap, 1, @i-1) LIKE ':_'
		RETURN N''
	
	SET @name = REVERSE(SUBSTRING(@htap, 1, @i-1))
	
	IF DATALENGTH(@name) <> DATALENGTH(@suffix)
	AND RIGHT(@name, DATALENGTH(@suffix)/2) = @suffix
		RETURN SUBSTRING(@name, 1, DATALENGTH(@name)/2 - DATALENGTH(@suffix)/2)
	
	RETURN @name
END
GO
